package service.impl;

import java.util.ArrayList;

import javax.annotation.Resource;

import model.FolderTreeNode;

import org.springframework.stereotype.Service;

import dao.FolderDAO;
import bean.Folder;
import service.FolderService;
import utils.FolderUtil;

@Service
public class FolderServiceImpl implements FolderService{
	
	@Resource
	private FolderDAO folderDao;
	
	public FolderTreeNode FolderTree() {
		FolderTreeNode tree = new FolderTreeNode(0,"Root","Root");
		tree.setHref("file/"+0);
		ArrayList<FolderTreeNode> folderTree = new ArrayList<FolderTreeNode>();
		ArrayList<Folder> roots = (ArrayList<Folder>) folderDao.findByBelongTo(0);
		if(roots.size() == 0) return null;
		for(Folder folder : roots){
			FolderTreeNode node = new FolderTreeNode(folder.getFolderId(), folder.getFolderName(), folder.getFolderDesc());
			node.setHref("file/"+node.getId());
			ArrayList<FolderTreeNode> nodes = getChildren(folder.getFolderId());
			node.setNodes(nodes);
			ArrayList<String> tags = new ArrayList<String>();
			if(nodes == null) tags.add("0");
			else tags.add(nodes.size()+"");
			node.setTags(tags);
			folderTree.add(node);
		}
		tree.setNodes(folderTree);
		//tree.setTags(folderTree.size()+"");
		ArrayList<String> tags2 = new ArrayList<String>();
		if(folderTree.size()==0) tags2.add("0");
		else tags2.add(folderTree.size()+"");
		tree.setTags(tags2);
		return tree;
	}
	
	public ArrayList<FolderTreeNode> getChildren(int belongTo){
		ArrayList<FolderTreeNode> children = new ArrayList<FolderTreeNode>();
		ArrayList<Folder> folderList = (ArrayList<Folder>) folderDao.findByBelongTo(belongTo);
		if(folderList.size() == 0) return null;
		for(Folder folder : folderList){
			FolderTreeNode node = new FolderTreeNode(folder.getFolderId(), folder.getFolderName(), folder.getFolderDesc());
			node.setHref("file/"+node.getId());
			ArrayList<FolderTreeNode> nodes = getChildren(folder.getFolderId());
			node.setNodes(nodes);
			/*if(nodes == null) node.setTags("0");
			else node.setTags(nodes.size()+"");*/
			ArrayList<String> tags = new ArrayList<String>();
			if(nodes == null) tags.add("0");
			else tags.add(nodes.size()+"");
			node.setTags(tags);
			children.add(node);
		}
		return children;
	}
	
	public boolean CreateFolder(Folder folder){
		if(FolderUtil.CreateFolder(folder.getFolderPath())){
			folderDao.save(folder);
			return true;
		}
		else return false;
	}
	
	public Folder FindById(int folderId){
		return folderDao.findById(folderId);
	}
	
	
}
